 <template>
  <div v-loading.fullscreen.lock="fullscreenLoading">
    <el-card class="box-card">
      <div slot="header" class="clearFix flex-container">
        <h2 v-if="currentId === ''">添加商品</h2>
        <h2 v-else>编辑商品</h2>
      </div>

      <div>
        <el-form ref="formData" :model="formData" label-width="200px">
          <el-form-item label="课程类型">
            <el-radio-group v-model="formData.category">
              <el-radio label="VIDEO">视频编辑</el-radio>
              <el-radio label="TEXT">图文编辑</el-radio>
              <el-radio label="VOICE">音频编辑</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item v-if="formData.category === 'VIDEO'" label="视频上传">
            <!-- 组件上传 【不允许修改视频】-->
            <el-upload
              class="upload-demo"
              ref="upload"
              :action="videoUploadUrl"
              accept="video/*"
              :on-success="handleVideoSuccess"
              :on-error="handleError"
              icon="el-icon-picture"
              :headers="token"
              :auto-upload="autoUpload"
              :on-change="changeUploadVideo"
              :on-progress="getProgress"
              v-if="!currentId"
            >
              <el-button class="add-style" size="small" type="primary">上传视频</el-button>
            </el-upload>

            <video v-if="formData.objectUrl" class="video-style" :src="formData.objectUrl" controls></video>
          </el-form-item>

          <!-- 图文编辑 -->
          <el-form-item v-if="formData.category === 'TEXT'" label="图文编辑">
            <vue-editor
              useCustomImageHandler
              @imageAdded="handleImageAdded"
              v-model="formData.content"
              class="eidtorStyle"
              placeholder="请输入文章信息"
            ></vue-editor>
          </el-form-item>
          <!-- 图文编辑 -->

          <!-- 音频编辑 -->
          <el-form-item v-if="formData.category === 'VOICE'" label="音频编辑">
            <!-- 组件上传 -->
            <el-upload
              class="upload-demo"
              ref="upload"
              :action="audioUploadUrl"
              accept="audio/mpeg, audio/ogg, application/ogg, audio/wav"
              :on-success="handleAudioSuccess"
              :on-error="handleError"
              icon="el-icon-picture"
              :headers="token"
              :on-progress="progressChange"
            >
              <el-button size="small" class="add-style" type="primary">上传音频</el-button>
            </el-upload>

            <audio v-if="formData.objectUrl" :src="formData.objectUrl" controls></audio>
          </el-form-item>
          <!-- 音频编辑 -->

          <el-form-item label="封面">
            <el-upload
              class="avatar-uploader"
              :action="uploadUrl"
              accept=".gif, .jpg, .jpeg, .bmp, .png"
              :headers="token"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
            >
              <img v-if="formData.coverUrl" :src="formData.coverUrl" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>

          <el-form-item
            label="名称"
            prop="title"
            :rules="[{required: true, message: '请输入标题', trigger: 'blur'}]"
          >
            <el-input class="input-width" v-model="formData.title" placeholder="请输入标题"></el-input>
          </el-form-item>

          <el-form-item
            v-if="formData.category !== 'VIDEO'"
            label="描述"
            prop="description"
            :rules="[{required: true, message: '请输入描述文本', trigger: 'blur'}]"
          >
            <el-input
              type="textarea"
              class="input-width"
              v-model="formData.description"
              placeholder="请输入描述"
            ></el-input>
          </el-form-item>

          <el-form-item label="分类">
            <el-radio-group v-model="formData.type">
              <el-radio
                v-for="item in category"
                :key="item.value"
                :label="item.value"
              >{{item.label}}</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item v-if="formData.type !== 'FREE'" label="价格">
            <el-input class="input-width" v-model="formData.price" placeholder="请输入价格"></el-input>
          </el-form-item>

          <el-form-item v-if="formData.type !== 'FREE'" label="分享价格">
            <el-input class="input-width" v-model="formData.sharePrice" placeholder="请输入分享价格"></el-input>
          </el-form-item>

          <el-form-item v-if="formData.category === 'VIDEO'" label="是否需要物流">
            <el-switch v-model="formData.logistics" active-color="#13ce66" inactive-color="#ccc"></el-switch>
          </el-form-item>

          <el-form-item>
            <el-button style="width:200px; margin-top: 20px" @click="uploadData" type="primary">完成</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
  </div>
</template>

<script>
import {
  createColumn,
  deleteColumn,
  updateColumn,
  createVideo,
  getVideo,
  updateVideo
} from "api/activate";
import { huaweiUploadImageUrl, baseUrl } from "src/config/env.js";
import { uploadVideo } from "api/upload.js";
import { getToken } from "src/util/auth";
import { setTimeout } from "timers";
import { VueEditor } from "vue2-editor";
var videoCategory = [
  {
    value: "FREE",
    label: "免费"
  },
  {
    value: "PAID",
    label: "付费"
  },
  {
    value: "GOODS",
    label: "出售商品"
  },
  {
    value: "SERVICE",
    label: "出售服务"
  }
];
var textCategory = [
  {
    value: "FREE",
    label: "免费"
  },
  {
    value: "PAID",
    label: "付费"
  }
];
import axios from "axios";

export default {
  data() {
    return {
      formData: {
        category: "VIDEO",
        title: "", //标题
        description: "",
        price: "", // 价格
        sharePrice: "", // 分享价格
        coverObjectId: "", // 封面id
        coverUrl: "", // 封面
        logistics: false,
        origin: "WEB",
        type: "FREE", // 分类

        // 视频、音频
        objectId: "",
        objectUrl: "",

        // 文章
        content: ""
      },
      token: { Authorization: "" },
      isUpdateVideo: false, // 是否上传视频
      uploadUrl: baseUrl + "/product/v1/uploadCover", // 上传封面地址
      videoUploadUrl: baseUrl + "/product/v1/uploadVideo", // 视频上传地址
      audioUploadUrl: baseUrl + "/product/v1/uploadVoice", // 音频上传地址
      dislogVisible: false, // 编辑分类卡片
      files: "", // 临时视频文件数据
      currentId: "", // 当前的商品id，修改商品的标识
      fullscreenLoading: false, // 页面loading
      autoUpload: false
    };
  },
  components: { VueEditor },
  computed: {
    // 商品分类
    category: function() {
      return this.formData.category === "VIDEO" ? videoCategory : textCategory;
    }
  },
  mounted() {
    this.init();
    this.token.Authorization = getToken();
  },
  methods: {
    // 视频本地上传【input上传】
    handleUploadVideo: function(event) {
      var files = event.target.files[0];
      var url = URL.createObjectURL(files);
      this.isUpdateVideo = true;

      // 本地预览
      this.files = files; // 临时视频文件数据
      this.formData.videoUrl = url;
    },
    changeUploadVideo(file, fileList) {
      this.isUpdateVideo = true; // 是否上传视频的标识

      var event = event || window.event;
      var files = event.target && event.target.files && event.target.files[0];
      if (!files) return;
      var url = URL.createObjectURL(files);

      this.formData.videoUrl = url;
    },
    handleError(res) {
      this.$message.error("视频上传失败");
    },
    // 触发上传视频界面
    changeVideo: function() {
      this.$refs.pickerVideo.click();
    },
    // 上传视频
    handleVideoSuccess(res) {
      if (res.status > 200) {
        this.$message.error(res.message);
        return;
      }
      this.$router.push("/activate");
    },
    // 上传封面
    handleAvatarSuccess(res) {
      if (res.status > 200) {
        this.$message.error(res.message);
        return;
      }
      this.formData.coverObjectId = res.data.coverObjectId;
      this.formData.coverUrl = res.data.coverUrl;
    },
    // 上传音频
    handleAudioSuccess(res, file) {
      if (res.status > 200) {
        this.$message.error(res.message);
        return;
      }
      this.formData.objectUrl = res.data;
    },
    // 上传数据
    uploadData() {
      this.$refs.formData.validate(valid => {
        if (valid) {
          let data = this.formData;
          switch (data.category) {
            case "VIDEO":
              delete data.content;
              this.update(data);
              break;
            case "TEXT":
              delete data.objectId;
              delete data.objectUrl;
              this.update(data);
              break;
            case "VOICE":
              delete data.content;
              delete data.objectId;
              this.update(data);
              break;
          }
        }
      });
    },

    // 上传数据接口处理
    update: function(data) {
      data = JSON.parse(JSON.stringify(data));

      if (this.currentId) {
        updateVideo(this.currentId, data).then(res => {
          this.fullscreenLoading = false;
          this.$message.success("修改成功");
          this.$router.push("/activate");
        });
      } else {
        delete data.coverUrl;
        createVideo(data).then(res => {
          this.fullscreenLoading = false;
          this.$message.success("创建成功");
          // 创建成功后才能上传视频需要获取objectId
          this.videoUploadUrl = this.videoUploadUrl + "/" + res.objectId;
          setTimeout(() => {
            if (data.category === "VIDEO") {
              this.$refs.upload.submit(); // 上传视频
            } else {
              this.$router.push("/activate");
            }
          }, 1000);
        });
      }
    },
    // 文本 =》 图片上传自定义
    handleImageAdded: function(file, Editor, cursorLocation, resetUploader) {
      // An example of using FormData
      // NOTE: Your key could be different such as:
      // formData.append('file', file)

      var formData = new FormData();
      formData.append("file", file);

      axios({
        url: baseUrl + "/qiniu/v1",
        method: "POST",
        data: formData,
        headers: {
          Authorization: getToken() || "no_value"
        }
      })
        .then(result => {
          let url = result.data.data; // Get url from response
          console.log(result);
          Editor.insertEmbed(cursorLocation, "image", url);
          resetUploader();
        })
        .catch(err => {
          console.log(err);
        });
    },
    // 上传视频
    uploadVideo(data) {
      if (this.isUpdateVideo) {
        uploadVideo(this.files).then(result => {
          if (result.status > 200) {
            this.$message.error(result.message);
            return;
          }

          data.objectId = result.data.videoObjectId;
          data.objectUrl = result.data.videoUrl;

          this.update(data);
        });
      } else {
        this.update(data);
      }
    },

    // 上传进度条
    getProgress(event, file, fileList) {
      console.log(event.percent);
      this.$router.push("/activate");
    },

    // 单个音频上传进度条
    progressChange(event, file, fileList) {
      this.percentage = Math.round(event.percent);
    },

    init() {
      let id = this.$route.params.id;
      if (id) {
        this.currentId = id;
        getVideo(id).then(res => {
          this.formData = res;
        });
      }
    }
  }
};
</script>

<style lang="scss" scoped>
@import "src/style/mixin";

.flex-container {
  @include fj(space-between);
  align-items: center;
}

.longTerm-style {
  color: #888;
  padding: 10px;
}

.input-width {
  width: 400px;
}
.upload-width {
  width: 400px;
}
.cascader-style {
  width: 300px;
  margin-bottom: 20px;
}

.widthBtn {
  width: 200px;
  margin: 20px 200px 0 0;
}

.upload-demo {
  width: 300px;
}

//----------------封面上传---------------
.avatar-uploader {
  // border: 1px dashed #d9d9d9;
  // border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  border: 2px dotted #f1f1f1;
  border-radius: 10px;
  width: 140px;
  height: 140px;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 40px;
  color: #8c939d;
  width: 140px;
  height: 140px;
  line-height: 140px;
  text-align: center;
}
.avatar {
  width: 140px;
  height: 140px;
  display: block;
}
//----------------封面上传---------------

// ----------------视频上传--------------
.video-uploader {
  cursor: pointer;
  position: relative;
  overflow: hidden;
  border: 2px dotted #f1f1f1;
  border-radius: 10px;
  width: 140px;
  height: 140px;

  .video-icon {
    margin: 40px auto;
    height: 48px;
    width: 48px;
    display: block;
  }
}

.video-style {
  width: 400px;
  margin-top: 20px;
}
// ----------------视频上传--------------

// ----------------编辑分类-------------------
.list-container {
  margin: 10px auto;
  width: 250px;
}
.list-style {
  @include fj(space-between);
  align-items: center;
  width: 200px;
  height: 50px;
  line-height: 50px;
  padding: 10px;
  border-radius: 10px;
}
.list-style:hover {
  background: #f1f1f1;
}
// ----------------编辑分类-------------------

.eidtorStyle {
  width: 70%;
}
</style>
